/*
 * author: Andriamananony, Meß, Falk
 */

package auftrag;

import java.util.ArrayList;
import java.util.Collections;

import util.Interval;

public class Ressource {
	private String strRessourceName;
	private ArrayList<Interval> mIntervals = new ArrayList<Interval>();

	public Ressource(String strRessourceName) {
		this.strRessourceName = strRessourceName;
	}

	@Override
	public String toString() {
		return this.strRessourceName;
	}
	
	public boolean addInterval(Interval pI){
		boolean bSuccess = true;
		for(Interval i : mIntervals){
			if(i.overlapsWith(pI)){
				bSuccess = false;
				break;
			}
		}
		if(bSuccess) {
			mIntervals.add(pI);
			Collections.sort(mIntervals);
			return true;
		}
		return false;
	}
	
	public Interval getFirstUnoccupiedInterval(int start, int d){
		Interval tmpCompare = new Interval(start,start+d);
		boolean bIntervalFound = false;
		while(!bIntervalFound){
			bIntervalFound = true;
			for(Interval i : mIntervals){
				if(i.overlapsWith(tmpCompare)){
					bIntervalFound = false;
					tmpCompare.moveTo(i.getEnd());
					break;
				} else if(i.compareTo(tmpCompare) == 1)
					break;
			}
		}
		return tmpCompare;
	}
	
	public boolean isOccupied(Interval pI){
		for(Interval i : mIntervals){
			if(i.overlapsWith(pI)){
				return true;
			}
			else if(i.compareTo(pI) > 0)
				return false;
		}
		return false;
	}
}
